﻿


using IotContract.Dtos.Clients;
using IotContract.Dtos.Servers.Process;
using IotContract.Enums;
using IotContract.Extensions;
using IotContract.Interfaces.Fmt;
using IotContract.Models;
using IotContract.Models.Clients.Hks;
using IotContract.Models.Fmts;
using IotContract.Models.Jobs;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;
using XT.Common.Enums;
using XT.Common.Interfaces;
using XT.Common.Services;


namespace IotServerService.Services.Remotes;
/// <summary>
/// 弃用
/// </summary>
public class RemoteHttpService : BaseApiService, IotContract.Interfaces.Fmt.IRemoteHttpService
{
    private readonly string resourceName = "api/ecs";

    private readonly string resourceOuterName = "api";

    private ILogService _logService;

    // 超时数目，目的是停止远程提交
    private int _timeoutCount = 0;
    public RemoteHttpService(IHttpClientFactory httpClientFactory, IApiConfig apiConfig, ILogService logService) : base(httpClientFactory, apiConfig)
    {
        _logService = logService;
    }

    /// <summary>
    /// 提交碟盘机碟盘完成
    /// </summary>
    /// <param name="tagNumber"></param>
    /// <returns></returns>
    public async Task<RemoteReturnModel<string>> CommitMagazine(int tagNumber)
    {
        if (tagNumber == 0)
        {
            return new RemoteReturnModel<string>();
        }
        try
        {

            var client = CreateHttpClient();

            var response = await client.GetAsync($"{resourceName}/stack/notify/{tagNumber}");

            var result = await response.ToResult<RemoteReturnModel<string>>();

            return result;

        }
        catch (Exception ex)
        {
            return new RemoteReturnModel<string>()
            {
                Msg = ex.Message,
            };
        }
    }

    /// <summary>
    /// 提交扫码枪数据
    /// </summary>
    /// <param name="unitTag"></param>
    /// <param name="trays"></param>
    /// <returns></returns>
    public async Task<RemoteReturnModel<EcsCvWrite>> CommitBcrResult(CvUnitTagDto unitTag, List<string> trays)
    {


        try
        {
            await _logService.LogContent($"beigin commit bcr,TagNumber {unitTag.TagNum},taskNo {unitTag.JobNumber}, {unitTag.EquipNum}", LogEnum.Info, unitTag.TagNum.ToString());



            BcrResultAll bcrResultAll = new BcrResultAll();





            bcrResultAll.ConveyorCode = unitTag.TagNum.ToString();
            bcrResultAll.TaskNo = unitTag.JobNumber.ToString();
            bcrResultAll.Trays = trays;



            var client = CreateHttpClient();
            var response = await client.PostAsJsonAsync($"{resourceName}/tray/transfer", bcrResultAll);

            var result = await response.ToResult<RemoteReturnModel<EcsCvWrite>>();



            if (!result.Flag)
            {

                await _logService.LogContent($"commit bcr groupnumber error {result.Msg},TagNumber {unitTag.TagNum},taskNo {unitTag.JobNumber}, {unitTag.EquipNum},trays {string.Join(',', trays)}", LogEnum.Error, unitTag.TagNum.ToString(),IotProgramType.IotServer.ToString(),true);
            }
            else
            {
                _timeoutCount = 0;
                await _logService.LogContent($"commit bcr TagNumber success {unitTag.TagNum}, groupnumber {unitTag.EquipNum},taskNo {unitTag.JobNumber}，trays {string.Join(',', trays)}", LogEnum.Info, unitTag.TagNum.ToString());
            }
            return result;
        }
        catch (TimeoutException ex)
        {
            _timeoutCount++;
            // 超时
            return new RemoteReturnModel<EcsCvWrite>
            {
                Msg = "Timeout"
            };
        }
        catch (Exception ex)
        {
            await _logService.LogContent($"commit bcr groupnumber error {ex.Message},{unitTag.EquipNum},traycode {unitTag.Tray1}", LogEnum.Error, unitTag.TagNum.ToString(), IotProgramType.IotServer.ToString(),true);

            return new RemoteReturnModel<EcsCvWrite>()
            {
                Msg = ex.Message
            };
        }

    }

    /// <summary>
    /// 获取远程SC任务
    /// </summary>
    /// <param name="jobId"></param>
    /// <returns></returns>
    public async Task<RemoteReturnModel<ScRemoteTask>> GetScRemoteTask(string jobId)
    {
        try
        {
            var client = CreateHttpClient();
            var response = await client.GetAsync($"{resourceName}/wareHouseTask/query?taskNumId={jobId}");

            var result = await response.ToResult<RemoteReturnModel<ScRemoteTask>>();
            return result;

        }
        catch (Exception ex)
        {
            // 超时等异常赋值code
            return new RemoteReturnModel<ScRemoteTask>()
            {
                Msg = ex.Message,
                Code = 100
            };
        }
    }

    /// <summary>
    /// 堆垛机状态提交
    /// </summary>
    /// <param name="taskDefine"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public async Task<RemoteReturnModel<EcsWriteData>> CommitScTaskID(ScTaskDefine taskDefine)
    {
        try
        {
            var client = CreateHttpClient();
            var response = await client.PostAsJsonAsync($"{resourceName}/task/notify", taskDefine);

            var result = await response.ToResult<RemoteReturnModel<EcsWriteData>>();

            return result;

        }
        catch (Exception ex)
        {
            return new RemoteReturnModel<EcsWriteData>()
            {
                Msg = ex.Message,
            };
        }
    }

    /// <summary>
    /// 提交移库任务
    /// </summary>
    /// <param name="scTask"></param>
    /// <returns></returns>
    public async Task<RemoteReturnModel<string>> CommitFmtMoveJob(ScTaskDefine scTask)
    {
        try
        {
            var client = CreateHttpClient();
            var response = await client.PostAsJsonAsync($"{resourceName}/relocation/notify", scTask);

            var result = await response.ToResult<RemoteReturnModel<string>>();
            return result;

        }
        catch (Exception ex)
        {
            return new RemoteReturnModel<string>()
            {
                Msg = ex.Message,
            };
        }
    }

    /// <summary>
    /// 根据库位获取入库任务
    /// </summary>
    /// <param name="stage"></param>
    /// <returns></returns>
    public async Task<RemoteReturnModel<List<ScEnterJob>>> GetEnterJobsByStage(StageArrayData stage)
    {
        try
        {
            var client = CreateHttpClient();
            var response = await client.PostAsJsonAsync($"{resourceName}/task/charge", stage);

            var result = await response.ToResult<RemoteReturnModel<List<ScEnterJob>>>();



            return result;

        }
        catch (Exception ex)
        {
            return new RemoteReturnModel<List<ScEnterJob>>
            {
                Msg = ex.Message,
            };
        }
    }

    /// <summary>
    /// 获取移库任务
    /// </summary>
    /// <param name="stage"></param>
    /// <returns></returns>
    public async Task<RemoteReturnModel<ScMoveTask>> GetFmtMoveJob(MoveStage stage)
    {
        try
        {
            var client = CreateHttpClient();
            var response = await client.GetAsync($"{resourceName}/relocation/query?stage={stage.Stage}");

            var result = await response.ToResult<RemoteReturnModel<ScMoveTask>>();
            return result;

        }
        catch (Exception ex)
        {
            return new RemoteReturnModel<ScMoveTask>()
            {
                Msg = ex.Message,
            };
        }
    }
    /// <summary>
    /// 是否远程超时
    /// </summary>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public bool IsRemoteTimeout()
    {
        return _timeoutCount > 3;
    }

    /// <summary>
    /// 提交设备状态结果
    /// </summary>
    /// <param name="equipStatus"></param>
    /// <returns></returns>
    public async Task<RemoteReturnModel<string>> CommitEquipStatus(RemoteEquipStatus equipStatus)
    {
        try
        {
            var client = CreateHttpClient();
            var response = await client.PostAsJsonAsync($"{resourceOuterName}/equipment/state", equipStatus);

            var result = await response.ToResult<RemoteReturnModel<string>>();



            return result;

        }
        catch (Exception ex)
        {
            return new RemoteReturnModel<string>()
            {
                Msg = ex.Message,
            };
        }
    }

    /// <summary>
    /// 提交设备报警结果
    /// </summary>
    /// <param name="equipStatus"></param>
    /// <returns></returns>
    public async Task<RemoteReturnModel<string>> CommitEquipWarn(RemoteEquipWarn equipWarn)
    {
        try
        {
            var client = CreateHttpClient();
            var response = await client.PostAsJsonAsync($"{resourceOuterName}/equipment/warning", equipWarn);

            var result = await response.ToResult<RemoteReturnModel<string>>();



            return result;

        }
        catch (Exception ex)
        {
            return new RemoteReturnModel<string>()
            {
                Msg = ex.Message,
            };
        }
    }

    /// <summary>
    /// 提交充放电报警
    /// </summary>
    /// <param name="error"></param>
    /// <param name="stage"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public async Task<RemoteReturnModel<string>> CommitFmtWarn(string error, int stage)
    {

        try
        {

            var client = CreateHttpClient();






            //json对象命名小驼峰式转换
            var str = JsonConvert.SerializeObject(new 
            {
                AlarmCode = error,
                Stage = stage
            }, Formatting.Indented, new JsonSerializerSettings
            {
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            });

            HttpContent content = new StringContent(str);
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

            var response = await client.PostAsync($"{resourceName}/alarm/charge", content);



            var result = await response.ToResult<RemoteReturnModel<string>>();



            return result;

        }
        catch (Exception ex)
        {
            return new RemoteReturnModel<string>()
            {
                Msg = ex.Message,
            };
        }
    }
  
    /// <summary>
    /// 提交充放电结果
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public async Task<RemoteReturnModel<string>> CommitChargeFMTResult(ChargeTrayResult data)
    {
        try
        {
            var client = CreateHttpClient();


            //json对象命名小驼峰式转换
            var str = JsonConvert.SerializeObject(data, Formatting.Indented, new JsonSerializerSettings
            {
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            });

            HttpContent content = new StringContent(str);
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

            var response = await client.PostAsync($"{resourceName}/charge/result", content);



            var result = await response.ToResult<RemoteReturnModel<string>>();

            return result;

        }
        catch (Exception ex)
        {
            return new RemoteReturnModel<string>()
            {
                Msg = ex.Message,
            };
        }
    }
    /// <summary>
    /// 提交充放电移库信息
    /// </summary>
    /// <param name="stageMove"></param>
    /// <returns></returns>
    public async Task<RemoteReturnModel<string>> CommitFmtMove(StageMoveInstruct stageMove)
    {
        try
        {
            var client = CreateHttpClient();
            var response = await client.PostAsJsonAsync($"{resourceName}/relocation/move", stageMove);

            var result = await response.ToResult<RemoteReturnModel<string>>();
            return result;

        }
        catch (Exception ex)
        {
            return new RemoteReturnModel<string>()
            {
                Msg = ex.Message,
            };
        }
    }

    /// <summary>
    /// 获取组盘信息
    /// </summary>
    /// <param name="trayNo"></param>
    /// <param name="equipCode"></param>
    /// <returns></returns>
    public async Task<RemoteReturnModel<TrayCellStatus>> GetTrayGroup(string trayNo, string equipCode, int id)
    {
        try
        {
            var client = CreateHttpClient();
            var response = await client.PostAsJsonAsync($"{resourceName}/ocv/tray", new { trayNo = trayNo, equipmentCode = equipCode, equipmentId = id });

            var result = await response.ToResult<RemoteReturnModel<TrayCellStatus>>();



            return result;

        }
        catch (Exception ex)
        {
            return new RemoteReturnModel<TrayCellStatus>()
            {
                Msg = ex.Message,
            };
        }
    }
    /// <summary>
    /// 提交OCV结果
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public async Task<RemoteReturnModel<OCVCellMain>> CommitOcvResult(OCVTrayResult data)
    {
        try
        {
            var client = CreateHttpClient();

            //json对象命名小驼峰式转换
            var str = JsonConvert.SerializeObject(data, Formatting.Indented, new JsonSerializerSettings
            {
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            });

            HttpContent content = new StringContent(str);
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

            var response = await client.PostAsync($"{resourceName}/ocv/result", content);



            var result = await response.ToResult<RemoteReturnModel<OCVCellMain>>();

            return result;

        }
        catch (Exception ex)
        {
            return new RemoteReturnModel<OCVCellMain>()
            {
                Msg = ex.Message,
            };
        }
    }
    /// <summary>
    /// 获取充放电复测配方数据
    /// </summary>
    /// <param name="trayCode"></param>
    /// <returns></returns>
    public async Task<RemoteReturnModel<ChargeStartData>> GetReTestChargeFMT(string trayCode)
    {
        try
        {
            var client = CreateHttpClient();

            var response = await client.GetAsync($"{resourceName}/get/retestformula/{trayCode}");

            var result = await response.ToResult<RemoteReturnModel<ChargeStartData>>();

            return result;

        }
        catch (Exception ex)
        {
            return new RemoteReturnModel<ChargeStartData>()
            {
                Msg = ex.Message,
            };
        }
    }

    /// <summary>
    /// 获取充放电配方数据
    /// </summary>
    /// <param name="trayCode"></param>
    /// <returns></returns>
    public async Task<RemoteReturnModel<ChargeStartData>> GetChargeFMTData(string trayCode)
    {
        try
        {
            var client = CreateHttpClient();

            var response = await client.GetAsync($"{resourceName}/get/formula/{trayCode}");

            var result = await response.ToResult<RemoteReturnModel<ChargeStartData>>();

            return result;

        }
        catch (Exception ex)
        {
            return new RemoteReturnModel<ChargeStartData>()
            {
                Msg = ex.Message,
            };
        }
    }

    /// <summary>
    /// 检验是否为NG托盘
    /// </summary>
    /// <param name="trayID"></param>
    /// <returns></returns>
    public async Task<RemoteReturnModel<string>> CheckNGResult(string trayID)
    {
        try
        {
            var client = CreateHttpClient();

            var response = await client.GetAsync($"{resourceName}/get/check/{trayID}");

            var result = await response.ToResult<RemoteReturnModel<string>>();

            return result;

        }
        catch (Exception ex)
        {
            return new RemoteReturnModel<string>()
            {
                Msg = ex.Message,
            };
        }
    }


    /// <summary>
    /// 筛选机获取电芯数据
    /// </summary>
    /// <param name="trayCode"></param>
    /// <returns></returns>
    public async Task<RemoteReturnModel<SelCellResult>> GetSelCellData(string trayCode, int groupNumber)
    {
        try
        {
            var client = CreateHttpClient();

            var response = await client.GetAsync($"{resourceName}/get/screendisk/{trayCode}/{groupNumber}");

            var result = await response.ToResult<RemoteReturnModel<SelCellResult>>();

            return result;

        }
        catch (Exception ex)
        {
            return new RemoteReturnModel<SelCellResult>()
            {
                Msg = ex.Message,
            };
        }
    }

    /// <summary>
    /// 筛选机获取电芯数据
    /// </summary>
    /// <param name="trayCode"></param>
    /// <returns></returns>
    public async Task<RemoteReturnModel<string>> CommitSelResult(string trayCode)
    {
        try
        {
            var client = CreateHttpClient();

            var response = await client.GetAsync($"{resourceName}/get/finishfilter/{trayCode}");

            var result = await response.ToResult<RemoteReturnModel<string>>();

            return result;

        }
        catch (Exception ex)
        {
            return new RemoteReturnModel<string>()
            {
                Msg = ex.Message,
            };
        }
    }
}
